/*
 * @lc app=leetcode.cn id=19 lang=typescript
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
    const p = new ListNode(0);
    p.next = head;
    let l: ListNode | null | any = p;
    let r: ListNode | null = p;
    for (let i = 0; i <= n; i++) {
        r = r?.next ? r.next : null
    }
    while (r) {
        r = r.next;
        l = l.next
    }
    l.next = l.next.next
    return p.next;
};
// @lc code=end

